<script setup>
	import {
		reactive,
		nextTick
	} from 'vue'

	import {
		onShow,
		onHide,
		onLoad
	} from '@dcloudio/uni-app'

	import cosUpload from '@/utils/upload'

	const props = defineProps({
		value: {
			type: String,
			default: '',
		},
		isDisable: {
			type: Boolean,
			default: false,
		},
	})

	const emits = defineEmits(['add'])

	const data = reactive({
		isAudio: false,
		recordAuth: false,
		speaking: false,
		value: '',
		url: '',
		type: 0,
		duration: 0,
		autoHeight: false
	})


	onLoad(() => {
		//微信 需要渲染后才启作用
		nextTick(() => {
			data.autoHeight = true
		})
	})

	const recorderManager = uni.getRecorderManager();

	function authTips() {
		uni.showModal({
			title: '提示',
			content: '您拒绝了麦克风权限，将导致功能不能正常使用，去设置权限？',
			confirmText: '去设置',
			cancelText: '取消',
			success: (res) => {
				if (res.confirm) {
					uni.openSetting({
						success: (res) => {
							if (res.authSetting['scope.record']) {
								console.log("已授权麦克风");
								data.recordAuth = true;
							} else {
								// 未授权
								wx.showModal({
									title: '提示',
									content: '您未授权麦克风，功能将无法使用',
									showCancel: false,
									confirmText: '知道了'
								})
							}
						}
					})
				}
			}
		})
	}


	const startRecord = () => {
		console.log('开始录音');

		const _permission = 'scope.record'
		uni.getSetting({
			success(res) {
				// 判断是否有相关权限属性
				if (res.authSetting.hasOwnProperty(_permission)) {
					// 属性存在，且为false，用户拒绝过权限
					if (!res.authSetting[_permission]) {
						authTips()
					} else {
						data.recordAuth = true;

						recorderManager.start({
							sampleRate: 16000, //采样率
							numberOfChannels: 1, //录音通道数
							encodeBitRate: 96000, //编码码率
							format: 'mp3', //音频格式，有效值aac/mp3
							frameSize: 1 //指定帧大小，单位 KB

						});
						recorderManager.onStart(() => {
							data.speaking = true
						})

						// 错误回调
						recorderManager.onError((res) => {
							console.log('recorder error', res)
							uni.showToast({
								icon: 'none',
								title: '系统出错，请重试'
							})
							data.speaking = false
						})
					}
				} else {

					// 属性不存在，需要授权
					uni.authorize({
						scope: _permission,
						success: () => {
							// 授权成功
							this._recordAuth = true
						},
						fail: (res) => {
							/**
							 * 104 未授权隐私协议
							 * 用户可能拒绝官方隐私授权弹窗，为了避免过度弹窗打扰用户，开发者再次调用隐私相关接口时，
							 * 若距上次用户拒绝不足10秒，将不再触发弹窗，直接给到开发者用户拒绝隐私授权弹窗的报错
							 */
							if (res.errno == 104) {
								uni.showModal({
									title: '温馨提示',
									content: '您拒绝了隐私协议，请稍后再试',
									confirmText: '知道了',
									showCancel: false,
									success: () => {}
								})
							} else {
								// 用户拒绝授权
								authTips()
							}
						}
					})
				}
			}
		})
	}
	const endRecord = () => {

		if (!data.recordAuth || !data.speaking) return

		console.log('录音结束');
		recorderManager.stop();
		recorderManager.onStop(async function(res) {
			//console.log('recorder stop' + JSON.stringify(res));
			//data.voicePath = res.tempFilePath;


			const {
				duration,
				tempFilePath
			} = res
			data.speaking = false

			data.duration = Math.round(duration / 1000);
			//上传音频文件
			const res1 = await new cosUpload({
				path: tempFilePath
			}).uploadFile()

			data.url = res1.url;
			//"type":"类型1：文字 2:图片 3：视频 4：音频"，
			data.type = 4 //
			emits('add', data)
		});
	}

	const sendText = () => {

		data.url = data.value;
		//"type":"类型1：文字 2:图片 3：视频 4：音频"，
		data.type = 1

		if (data.value) {
			emits('add', data);
			data.value = "";
		} else {

		}


		// emits('add', data)
	}
</script>

<template>
	<view class="footer">
		<template v-if="!props.isDisable">
			<template v-if="data.isAudio">
				<view class="pic pic1" @click="data.isAudio = false">
					<image src="/static/icon/text.png" mode="aspectFit" />
				</view>
				<text class="text speak" @touchstart="startRecord" @touchend="endRecord">按住说话 Publish voice
					message</text>

				<view class="voice-line-wrap" v-if="data.speaking" :style="{
									  '--line-height': '26rpx',
									  '--line-start-color': 'royalblue',
									  '--line-end-color': 'indianred',
									}">
					<view class="voice-line one"></view>
					<view class="voice-line two"></view>
					<view class="voice-line three"></view>
					<view class="voice-line four"></view>
					<view class="voice-line five"></view>
					<view class="voice-line six"></view>
					<view class="voice-line seven"></view>
					<view class="voice-line six"></view>
					<view class="voice-line five"></view>
					<view class="voice-line four"></view>
					<view class="voice-line three"></view>
					<view class="voice-line two"></view>
					<view class="voice-line one"></view>
				</view>
			</template>
			<template v-else>
				<view class="pic" @click="data.isAudio = true">
					<image src="/static/icon/audio.png" mode="aspectFit" />
				</view>
				<textarea :auto-height="data.autoHeight" class="text" cursor-spacing="16px" :maxlength="1000"
					:show-confirm-bar="false" v-model="data.value" />
				<text class="send" v-if="!!data.value" @click="sendText">发送</text>
			</template>
		</template>
		<template v-else>
			<text class="text speak">旁听资格 限制发言 点击申请领取此组资料</text>
		</template>
	</view>
</template>

<style lang="scss" scoped>
	.footer {
		position: fixed;
		bottom: 0;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		width: 100%;
		padding: 34rpx 50rpx 50rpx;
		min-height: 150rpx;
		border-top: 1rpx solid rgb(168, 168, 168);
		background-color: #fff;
		z-index: 999;

		.pic {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 67rpx;
			height: 66rpx;
			box-sizing: border-box;
			border: 0.5rpx solid rgb(166, 166, 166);
			border-radius: 12rpx;

			>image {
				transform: rotate(180deg);
				width: 28rpx;
				height: 36rpx;
			}

			&.pic1>image {
				transform: rotate(0);
				width: 20rpx;
				height: 20rpx;
			}
		}

		.text {
			margin: 0 6rpx;
			padding: 15rpx 0;
			padding-left: 12rpx;
			flex: 1;
			height: 66rpx;
			max-height: 216rpx;
			box-sizing: border-box;
			border: 0.5rpx solid rgb(166, 166, 166);
			border-radius: 12rpx;
			color: rgb(110, 110, 110);
			font-size: 18rpx;
			font-weight: 600;
			line-height: 36rpx;
			text-align: left;
			min-height: 66rpx;
			white-space: pre-wrap
		}

		.send {
			width: 100rpx;
			height: 64rpx;
			box-sizing: border-box;
			border: 0.5rpx solid rgb(166, 166, 166);
			border-radius: 12rpx;
			color: rgb(110, 110, 110);
			font-size: 26rpx;
			font-weight: 600;
			line-height: 64rpx;
			text-align: center;
		}

		.speak {
			color: rgb(97, 97, 97);
			font-size: 15rpx;
			font-weight: 600;
			line-height: 36rpx;
			text-align: center;
		}
	}
</style>